package net.adetech.dcweb.core.common.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.adetech.dcweb.core.common.entity.CommonAdminuser;
import net.adetech.dcweb.core.common.service.ICommonAdminuserService;
import net.adetech.utils.UtilsCommon;
import net.adetech.utils.UtilsCondition;
import net.adetech.utils.UtilsEncryption;
import net.adetech.utils.spring.PageBean;
import net.adetech.web.utils.UtilsUI;
import net.adetech.web.utils.UtilsWeb;
import net.adetech.web.utils.spring.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by auto on 2016/10/21.
 */
@RestController
public class CommonAdminuserRestController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(CommonAdminuserRestController.class);

    @Autowired
    private ICommonAdminuserService iCommonAdminuserService;

    @PostMapping(value = "/common/adminuser", produces = "application/json")
    public String add(HttpServletRequest request, HttpServletResponse response) {
        CommonAdminuser entity = this.wrapper(CommonAdminuser.class, request);
        try {
            entity.setPassword(UtilsEncryption.md5(entity.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        entity = iCommonAdminuserService.save(entity);
        response.setStatus(HttpServletResponse.SC_CREATED);
        opLog(request, logger, "增加", "");
        return UtilsUI.data(entity);
    }


    /**
     * 【账号】登录
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/common/adminuser/login", produces = "application/json")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String usern = UtilsWeb.getString(request, "usern");
        String password = UtilsWeb.getString(request, "password");
        CommonAdminuser commonAdminuser = this.iCommonAdminuserService.findByUsern(usern);
        try {
            password = UtilsEncryption.md5(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject result = new JSONObject();

        if (commonAdminuser != null && commonAdminuser.getPassword().equals(password)) {
            String ip = UtilsWeb.getIp(request);
            commonAdminuser.setLastLoginDate(new Date());
            commonAdminuser.setLastLoginIp(ip);
            this.iCommonAdminuserService.update(commonAdminuser);
            request.getSession().setAttribute("adminuser", commonAdminuser);
            JSONObject obj = new JSONObject();
            obj.put("status", "ok");
            obj.put("adminuser", commonAdminuser);
            return obj.toJSONString();
        } else {
            return UtilsUI.fail();
        }


    }


    /**
     * 【账号】单条
     *
     * @param id
     * @param response
     * @param request
     * @return
     */
    @GetMapping(value = "/common/adminuser/{id}", produces = "application/json")
    public String detail(@PathVariable Long id, HttpServletResponse response, HttpServletRequest request) {
        //session panduan
        CommonAdminuser entity = iCommonAdminuserService.find(id);
        if (null == entity) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return null;
        }
        opLog(request, logger, "查看", "");
        return JSONObject.toJSONString(entity);
    }


    /**
     * 【帐号】修改
     *
     * @param request
     * @param id
     * @param response
     */

    @PutMapping(value = "/common/adminuser/{id}", produces = "application/json")
    public String update(HttpServletRequest request, @PathVariable Long id, HttpServletResponse response) {
        CommonAdminuser requestEntity = this.wrapper(CommonAdminuser.class, request);

        JSONObject jsonObject = new JSONObject();

        if (requestEntity == null || requestEntity.getSex() == null || requestEntity.getRealName() == null || requestEntity.getPhone() == null || requestEntity.getPoliceNo() == null) {
            UtilsUI.fail();
            return jsonObject.toJSONString();
        }
        CommonAdminuser currentEntity = iCommonAdminuserService.find(id);
        currentEntity.setSex(requestEntity.getSex());
        currentEntity.setRealName(requestEntity.getRealName());
        currentEntity.setPhone(requestEntity.getPhone());
        currentEntity.setPoliceNo(requestEntity.getPoliceNo());
        CommonAdminuser commonAdminuser = (CommonAdminuser) request.getSession().getAttribute("adminuser");
        int rs = iCommonAdminuserService.update(currentEntity);
        opLog(request, logger, "修改", "");
        if (rs > 0) {
            return UtilsUI.ok();

        } else {
            return UtilsUI.fail();

        }
    }

    /**
     * 【帐号】修改密码
     *
     * @param request
     * @param id
     * @param response
     */

    @PutMapping(value = "/common/adminuser/updpwd", produces = "application/json")
    public String updpwd(HttpServletRequest request, Long id, String oldpwd, String newpwd, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        if (newpwd.length() < 4) {
            return UtilsUI.tip("password too short");
        }
        oldpwd = UtilsEncryption.md5(oldpwd);
        newpwd = UtilsEncryption.md5(newpwd);
        CommonAdminuser currentEntity = iCommonAdminuserService.find(id);
//        CommonAdminuser commonAdminuser = (CommonAdminuser) request.getSession().getAttribute("adminuser");
//        if (commonAdminuser!=null&&commonAdminuser.getId() != id) {
//            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
//            jsonObject.put("status", "fail_only_update_own_account");
//            return jsonObject.toJSONString();
//        }
        if (currentEntity != null && currentEntity.getPassword().equals(oldpwd)) {
            currentEntity.setPassword(newpwd);
        } else if (!currentEntity.getPassword().equals(oldpwd)) {
            return UtilsUI.tip("olderror");

        } else {
            return UtilsUI.fail();

        }
        int rs = iCommonAdminuserService.update(currentEntity);
        opLog(request, logger, "修改密码", "");
        if (rs > 0) {
            return UtilsUI.ok();
        } else {
            return UtilsUI.fail();
        }
    }

    /**
     * 【帐号】审批人
     *
     * @param request
     * @param
     * @param response
     */

    @GetMapping(value = "/common/auditusers", produces = "application/json")
    public String auditusers(HttpServletRequest request, HttpServletResponse response) {
        JSONArray jsonArray = new JSONArray();

        List<CommonAdminuser> commonAdminuserList = iCommonAdminuserService.findByRoleNo();
        opLog(request, logger, "审批人", "");
        for (CommonAdminuser commonAdminuser : commonAdminuserList) {
            response.setStatus(HttpServletResponse.SC_OK);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("value", commonAdminuser.getId());
            jsonObject.put("text", commonAdminuser.getRealName());
            jsonArray.add(jsonObject);
        }
        return jsonArray.toJSONString();

    }

    /**
     * 【帐号】是否有用户信息
     *
     * @param request
     * @param
     * @param response
     */

    @GetMapping(value = "/common/adminuser/islogin", produces = "application/json")
    public String islogin(HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        CommonAdminuser commonAdminuser = (CommonAdminuser) request.getSession().getAttribute("adminuser");
        opLog(request, logger, "【帐号】是否有用户信息", "");
        if (commonAdminuser != null && commonAdminuser.getId() != 0) {
            return UtilsUI.ok();

        } else {
            return UtilsUI.fail();
        }


    }

    @PostMapping(value = "/common/adminuser/exit", produces = "application/json")
    public String exit(HttpServletRequest request, HttpServletResponse response) {
        CommonAdminuser commonAdminuser = (CommonAdminuser) request.getSession().getAttribute("adminuser");
        opLog(request, logger, "【帐号】是否有用户信息", "");
        if (commonAdminuser != null && commonAdminuser.getId() != 0) {
            request.getSession().invalidate();
            return UtilsUI.ok();
        } else {
            return UtilsUI.fail();
        }


    }


    @DeleteMapping(value = "/common/adminuser", produces = "application/json")
    public String delete(HttpServletRequest request, HttpServletResponse response) {
        String idsStr = UtilsWeb.getString(request, "ids");
        if ("".equals(idsStr)) {
            return UtilsUI.tip("请传入ids参数");
        }
        String[] ids = idsStr.split(",");
        if (null != ids && ids.length > 0) {
            List
                    <Long> idsLong = new ArrayList<>(0);
            for (int i = 0; i < ids.length; i++) {
                idsLong.add(UtilsCommon.getLong(ids[i]));
            }
            iCommonAdminuserService.delete(idsLong);
        }
        opLog(request, logger, "删除", "");
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return null;
    }

    @GetMapping(value = "/common/adminusers", produces = "application/json")
    public String page(HttpServletRequest request) {
        Integer nowPage = UtilsWeb.getInteger(request, "nowPage");
        Integer pageSize = UtilsWeb.getInteger(request, "pageSize");
        if (null == nowPage || nowPage <= 0) {
            return UtilsUI.tip("未传入nowPage参数，或者nowPage参数错误！");
        }
        if (null == pageSize || pageSize <= 0) {
            return UtilsUI.tip("请传入pageSize参数，或者pageSize参数错误！");
        }
        PageBean<CommonAdminuser> pageBean = iCommonAdminuserService.page(nowPage,
                pageSize, UtilsCondition.getConditionEntity(request.getParameterMap()));
        opLog(request, logger, "分页查看", "");
        return UtilsUI.datagrid(pageBean);
    }
}